#coding=utf-8
#Boa:FramePanel:PanelFund

import wx

import DlgCustomerChoice
import DlgPopupSupplier


from MyListCtrl import MyFundCustmoerListCtrl,MyListCtrlOrderAmountAllocted,MyListCtrlOrderVoucherList
from MyListCtrl import MyListCtrlPurContent, MyOrderContentListCtrl
from ctrlAider import *
from product import *

[wxID_PANELFUND, wxID_PANELFUNDBTNSEARCH, wxID_PANELFUNDBTNSHOWPEER, 
 wxID_PANELFUNDTCPEERNAME, wxID_PANELFUNDTCSTAT, wxID_PANELFUNDTPEER, 
] = [wx.NewId() for _init_ctrls in range(6)]

[Type_Customer, Type_Supplier] = [0,1]

class PanelFund(wx.Panel):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Panel.__init__(self, id=wxID_PANELFUND, name=u'PanelFund',
              parent=prnt, pos=wx.Point(252, 76), size=wx.Size(1028, 694),
              style=wx.TAB_TRAVERSAL)
        self.SetClientSize(wx.Size(1020, 660))
        self.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False,u'Arial'))
        self.SetBackgroundColour(wx.Colour(183, 209, 173))
        self.Center(wx.BOTH)

        self.tPeer = wx.StaticText(id=wxID_PANELFUNDTPEER,
              label=u'\u5ba2\u6237\u540d\u79f0\uff1a', name=u'tPeer',
              parent=self, pos=wx.Point(10, 32), size=wx.Size(90, 24), style=0)

        self.tcPeerName = wx.TextCtrl(id=wxID_PANELFUNDTCPEERNAME,
              name=u'tcPeerName', parent=self, pos=wx.Point(100, 24),
              size=wx.Size(248, 28), style=0, value=u'')

        self.btnSearch = wx.Button(id=wxID_PANELFUNDBTNSEARCH,
              label=u'\u67e5\u627e', name=u'btnSearch', parent=self,
              pos=wx.Point(380, 24), size=wx.Size(80, 29), style=0)
        self.btnSearch.Bind(wx.EVT_BUTTON, self.OnBtnSearchButton,
              id=wxID_PANELFUNDBTNSEARCH)

        self.tcStat = wx.TextCtrl(id=wxID_PANELFUNDTCSTAT, name=u'tcStat',
              parent=self, pos=wx.Point(10, 63), size=wx.Size(768, 73),
              style=wx.RAISED_BORDER | wx.TE_MULTILINE, value=u'')

        self.btnShowPeer = wx.Button(id=wxID_PANELFUNDBTNSHOWPEER, label=u'+',
              name=u'btnShowPeer', parent=self, pos=wx.Point(348, 24),
              size=wx.Size(24, 29), style=0)
        self.btnShowPeer.Bind(wx.EVT_BUTTON, self.OnBtnShowPeerButton,
              id=wxID_PANELFUNDBTNSHOWPEER)

    def __init__(self, parent, type):
        self._init_ctrls(parent)
        
        self.myInit(type)
        
    def myInit(self, type):
        self.m_peer = None
        
        self.nb = wx.Notebook(self)
        
        if(type == Type_Customer):
            self.popupWin = DlgCustomerChoice.create(self)
            self.lc = MyFundCustmoerListCtrl(self)
            self.lcAlloct = MyListCtrlOrderAmountAllocted(self, CDataCustomer)
            self.lcPayment = MyListCtrlOrderVoucherList(self.nb)
            self.lcPayment.setOrderStyle(CDataCustomer)
            
            self.lcContent = MyOrderContentListCtrl(self.nb)
            
        elif(type == Type_Supplier):
            self.popupWin = DlgPopupSupplier.create(self)
            self.lc = MyFundCustmoerListCtrl(self, type=MyFundCustmoerListCtrl.Type_Supplier)
            self.lcAlloct = MyListCtrlOrderAmountAllocted(self, CDataSupplier)
            self.lcPayment = MyListCtrlOrderVoucherList(self.nb)
            self.lcPayment.setOrderStyle(CDataSupplier)
            
            self.lcContent = MyListCtrlPurContent(self.nb)
        
        self.tcPeer = MyPopupTextCtrlDecorator(self.tcPeerName, self.popupWin)
        
        self.lc.SetSize(wx.Size(1000, 300))
        self.lc.Move(wx.Point(10,140))
        
        self.lc.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnListItemSelected)
        
        self.lcAlloct.Move(wx.Point(10,450))
        self.lcAlloct.SetSize(wx.Size(1000, 175))
        self.lcAlloct.Show(False)
        
        self.nb.Move(wx.Point(10,450))
        self.nb.SetSize(wx.Size(1000, 175))
        self.nb.Show(False)
        
        self.nb.AddPage(imageId=-1, page=self.lcContent, select=True,
                    text=u'产品明细')
                    
        self.nb.AddPage(imageId=-1, page=self.lcPayment, select=False,
                    text=u'付款明细')
                    

    def setModeLinkVoucher(self, detailObj):
        self.curDetailObj = detailObj
        self.lc.Bind(wx.EVT_LEFT_DCLICK, self.OnDClickItem)
        
    def getLinkVoucherId(self):
        return self.linkVoucherId
    
    def OnDClickItem(self, event):
        voucherObj = self.lc.getSelectedVoucher()
        if voucherObj is None:
            msg = u'请选择收款单'
            dlg = wx.MessageDialog(self, msg, u'提示消息', wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            return
        
        detailAmount = self.curDetailObj.getValue(self.curDetailObj.COL_MONEY)
        voucherAmount = voucherObj.getValue(voucherObj.COL_MONEY)
        if isinstance(voucherObj, CDataVoucherSupplier):
            voucherAmount = -voucherAmount
            
        if (detailAmount != voucherAmount):
            msg = u'账户变动金额%d与收款单金额%d不匹配，请重新核对' %(detailAmount, voucherAmount)
            dlg = wx.MessageDialog(self, msg, u'提示消息', wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            return
            
        details = voucherObj.getAccountDetail()
        if details:
            msg = u'该收款单已经关联了其他资金变动：\n%s' %details
            dlg = wx.MessageDialog(self, msg, u'提示消息', wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            return 
            
        self.linkVoucherId = voucherObj.getKeyVal()
            
        self.GetParent().EndModal(wx.ID_OK)
    
    def OnListItemSelected(self, event):
        item = self.lc.GetNextItem(-1, state = wx.LIST_STATE_SELECTED)
        if self.lc.isVoucher(item):
            self.lcAlloct.Show(True)   
            self.nb.Show(False)

            self.lcAlloct.refresh({'voucherId':self.lc.getBillId(item), 'show':'alloct'})  
            
        elif self.lc.isOrder(item):
            self.lcAlloct.Show(False)   
            self.nb.Show(True)
            
            self.lcContent.refresh({'billId':self.lc.getBillId(item)})
            self.lcPayment.refresh({'billId':self.lc.getBillId(item)})
        
        
    def refreshStat(self):
        str = u'总销售单数：%d  总收款单数：%d\n'\
                u'销售总金额：%.2f  收款总金额：%.2f  优惠总金额：%.2f\n'\
                u'欠款总金额：%.2f'\
                %(self.lc.m_saleCnt, self.lc.m_voucherCnt,
                 self.lc.m_total, self.lc.m_paid, self.lc.m_discount,
                 self.lc.m_total - self.lc.m_paid - self.lc.m_discount)
        
        self.tcStat.SetValue(str)

    def setBtnAccount(self, money):
        self.btnLink = wx.Button(self)
        self.btnLink.SetLabel(u'关联到选中销售单')
        self.btnLink.SetSize(self.btnLink.GetBestSize())
        self.btnLink.Move((400, 32))
        self.btnLink.Bind(wx.EVT_BUTTON, self.OnBtnLinkButton)
    
        self.amount = money
        
    def getLinkVoucherId(self):
        return self.linkVoucherId 
    
    def setSelectObj(self, obj):
        '''设置选中客户'''
        self.setSelectPeer(obj)
        
    def setCustomer(self, obj):
        '''设置选中客户'''
        self.setSelectObj(obj)
        
    def getSelectPeer(self):
        return self.m_peer
    
    def setSelectPeer(self, obj):
        if (obj is not None):
            #if None, we keep old value
            self.m_peer = obj
            
        if (self.m_peer is not None):
            name = self.m_peer.getValue(self.m_peer.COL_NAME)
            #self.lc.refresh({'peerId':self.m_peer.getValue(self.m_peer.COL_ID)})
            #self.refreshStat()
            self.refresh()
        else:
            name = ''
            
        self.tcPeer.ChangeValue(name)
        # refresh()在没有设置Peer时，显示全部，会带来效率问题
        #self.refresh()
                                
    def getPopupWinPos(self):
        posBtn = self.tcPeer.ClientToScreen((0,0))
        posPrt = self.ClientToScreen((0,0))
        sz =  self.tcPeer.GetSize()
        return (posPrt.x, posBtn.y + sz.GetHeight())
    
    def refresh(self):
        filter = {}
        if self.m_peer is not None:
            filter['peerId'] = self.m_peer.getValue(self.m_peer.COL_ID)
      
        cnt = self.lc.refresh(filter)
        #self.lc.refreshRemain()
        self.refreshStat()
    
    def OnBtnLinkButton(self, event):
        '''设置收款单与账户变动的关系'''
        obj = self.lc.getSelectedVoucher()
        if (obj is None):
            msg = u'请选择收款单，没有符合需要的收款单，请新建一个'
            dlg = wx.MessageDialog(self, msg, u'提示消息', wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            return
        
        if (self.amount != obj.getValue(obj.COL_MONEY)):
            msg = u'账户变动金额%d与收款单金额不匹配，请重新选择收款单' %self.amount
            dlg = wx.MessageDialog(self, msg, u'提示消息', wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            return
        
        self.linkVoucherId = obj.getValue(obj.COL_ID)
        self.EndModal(wx.ID_OK)
        
    def OnBtnSearchButton(self, event):
        if self.tcPeer.GetValue() == '':
            self.m_peer = None
            msg = u'没有选择客户，数据量大会导致载入缓慢，是否继续?'
            dlg = wx.MessageDialog(self, msg,u'提示',wx.YES_NO|wx.ICON_QUESTION)
            if not(dlg.ShowModal() == wx.ID_YES):
                return
        
        self.refresh()

    def OnBtnShowPeerButton(self, event):
        self.tcPeer.resetPopupWinPos()
        self.popupWin.Show()
        event.Skip()

